package lvbu.wang.lvbuoperator.ui.scan;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.qing.library.widget.CustomProgress;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lvbu.wang.lvbuoperator.R;
import lvbu.wang.lvbuoperator.adapter.BluetoothListAdapter;
import lvbu.wang.lvbuoperator.bean.BluetoothInfoBean;
import lvbu.wang.lvbuoperator.bean.MotorInfo;
import lvbu.wang.lvbuoperator.constants.ConstantsValue;
import lvbu.wang.lvbuoperator.constants.RouteConstant;
import lvbu.wang.lvbuoperator.core.App;
import lvbu.wang.lvbuoperator.core.BaseActivity;
import lvbu.wang.lvbuoperator.http.IotHttpHelp;
import lvbu.wang.lvbuoperator.manager.ThreadPool;
import lvbu.wang.lvbuoperator.services.BluetoothLEService;
import lvbu.wang.lvbuoperator.ui.paramset.ui.IotParamSetActivity;
import lvbu.wang.lvbuoperator.widget.CustDialog;


/**
 * Created by DaiQing.Zha on 2016/11/3 0003.
 */
public class IotBluetoothListActivity extends BaseActivity {

    private static final int REQUEST_ENABLE_BT = 1;
    private static final long SCAN_PERIOD = 25 * 1000;  //25秒后停止查找搜索.
    private ListView mLstBluetooth; //蓝牙列表
    private ImageView mImgRefresh;  //刷新
    private TextView mTvScan;   //扫描
    private CustomProgress mCustomProgress;  //自定义进度条
    private Dialog mDialog;
    private BluetoothListAdapter mLeDeviceListAdapter;
    private List<BluetoothInfoBean> mBluetoothInfoBeanList;
    private BluetoothAdapter mBluetoothAdapter;
    private Handler mHandler;
    private List<String> mLstScanedAddress;    //已扫描到的蓝牙地址
    LinearInterpolator mLinearInterpolator;   //插入器
    Animation mOperatingAnim;                 //动画
    private String mSelectedAddress;       //选中的蓝牙地址
    private boolean mIsOnShow = true;    //页面是否正在显示
    private boolean mScanning = false; //是否正在扫描---true：正在扫描，false:扫描已停止
    private BluetoothAdapter.LeScanCallback mLeScanCallback;
    /**
     * 广播接收器
     */
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { // 定义广播接收器，接收蓝牙消息
        @Override
        public void onReceive(Context context, final Intent intent) {
            if (intent.getAction().equals(ConstantsValue.ACTION_BLUETOOTH_CONNECT_STATE_CHANGED)) { //蓝牙状态改变
                if (BaseActivity.getMotorDefault_bluetooth_connect_state(IotBluetoothListActivity.this) == BluetoothLEService.Bluetooth_CONNECTED){
                    mCustomProgress.dissMiss();
                    if (!mDialog.isShowing()){
                        mDialog.show();
                    }
                }
                if (BaseActivity.getMotorDefault_bluetooth_connect_state(IotBluetoothListActivity.this) == BluetoothLEService.Bluetooth_UNCONNECT){
                    if (mIsOnShow){
                        mCustomProgress.dissMiss();
                    }
                }
            }
        }
    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth_list);
        View view = LayoutInflater.from(IotBluetoothListActivity.this).inflate(R.layout.view_of_confirm_connected,null);
        CustDialog.Builder builder = new CustDialog.Builder(IotBluetoothListActivity.this, view);
        builder.setOKDialogButton(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                getMotorInfoByBleAddress(mSelectedAddress);
            }
        });
        builder.setCancelDialogButton(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                BluetoothLEService.disConnect();
            }
        });
        mDialog = builder.create();
        mDialog.setCancelable(false);
        mBluetoothInfoBeanList = new ArrayList<>();
        mLstScanedAddress = new ArrayList<>();
        registerBroadcast();
    }
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void init() {
        mLstBluetooth = findView(R.id.lst_bluetooth);
        mImgRefresh = findView(R.id.img_refresh);
        mTvScan = findView(R.id.tv_scan);
        mHandler = new Handler();
        mLinearInterpolator = new LinearInterpolator();
        mOperatingAnim = AnimationUtils.loadAnimation(this, R.anim.rotate_scan);
        mOperatingAnim.setInterpolator(mLinearInterpolator);
        mCustomProgress = new CustomProgress(this);
        // 检查当前手机是否支持ble 蓝牙,如果不支持退出程序
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            showToastMsg(getString(R.string.toast_comm_bleNotSupported));
            finish();
        }
        // 初始化 Bluetooth adapter, 通过蓝牙管理器得到一个参考蓝牙适配器(API必须在以上android4.3或以上和版本)
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        // 检查设备上是否支持蓝牙
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, R.string.toast_comm_errorBluetoothNotSupported, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        mImgRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mScanning){ //正在扫描
                    scanLeDevice(false);
                }else{
                    mLstScanedAddress.clear();
                    mBluetoothInfoBeanList.clear();
                    mLeDeviceListAdapter.notifyDataSetChanged();
                    scanLeDevice(true);
                }
            }
        });
        mLstBluetooth.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                BaseActivity.saveMotorDefault_bluetooth_connect_state(IotBluetoothListActivity.this, BluetoothLEService.Bluetooth_UNCONNECT);    //设置蓝牙状态为未连接
                mSelectedAddress = mBluetoothInfoBeanList.get(position).getAddress();
                MotorInfo motorInfo = App.getInstance().getMotorInfo();
                motorInfo.setBluetoothAddress(mSelectedAddress);
                App.getInstance().setMotor(motorInfo);
                setBluetoothAddress(IotBluetoothListActivity.this, mSelectedAddress);
                Log.e("BLETOOTH","mSelectedAddress = " + mSelectedAddress);
                BluetoothLEService.connect();
                scanLeDevice(false);
                mCustomProgress.show(IotBluetoothListActivity.this, "正在连接蓝牙", false, null, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CustomProgress.dissMiss();
                        BluetoothLEService.disConnect();
                    }
                });
            }
        });
        mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

            @Override
            public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mLstScanedAddress.contains(device.getAddress())){
                            for (int i = 0; i < mBluetoothInfoBeanList.size(); i ++){
                                if (mBluetoothInfoBeanList.get(i).getAddress().equals(device.getAddress())) mBluetoothInfoBeanList.get(i).setRssi(rssi + "");
                            }
                        }else if ((("Lvbu motor".equalsIgnoreCase(device.getName()) || "Lvbu bike".equalsIgnoreCase(device.getName())) && rssi > -70 && rssi < 0)){//(("Lvbu motor".equalsIgnoreCase(device.getName()) || "Lvbu bike".equalsIgnoreCase(device.getName())) && rssi > -70 && rssi < 0)
                            BluetoothInfoBean bluetoothInfoBean = new BluetoothInfoBean();
                            bluetoothInfoBean.setAddress(device.getAddress());
                            bluetoothInfoBean.setRssi(rssi + "");
                            bluetoothInfoBean.setName(device.getName());
                            mLstScanedAddress.add(device.getAddress());
                            mBluetoothInfoBeanList.add(bluetoothInfoBean);
                        }
                        mLeDeviceListAdapter.notifyDataSetChanged();
                    }
                });
            }
        };
        getSupportActionBar().setTitle(getString(R.string.app_iot_name));
    }
    /**
     * 通过蓝牙地址获取电机信息
     */
    private void getMotorInfoByBleAddress(final String address) {
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                Map<String, Object> queryStrings = new HashMap<String, Object>();
                queryStrings.put("bluetoothAddress", address);
                String source = IotHttpHelp.getData(RouteConstant.Get_JsonMotor_MotorInfo_byBluetoothAddress, queryStrings, true, IotBluetoothListActivity.this);
                Log.e("mainVBN","source = " + source + " token = " + getToken() + " address = " + address);
                if (IotHttpHelp.checkSource(source)) {
                    MotorInfo motorInfo = new Gson().fromJson(source, MotorInfo.class);
                    if (motorInfo.getMotorId() > 0) {
                        String statusCode = motorInfo.getStatusCode();
                        Bundle bundle = new Bundle();
                        bundle.putLong("motorId", motorInfo.getMotorId());
                        bundle.putBoolean("isOnline", motorInfo.getIsOnline());
                        bundle.putString("imei", motorInfo.getImei());
                        bundle.putString("bluetoothAddress", motorInfo.getBluetoothAddress());
                        bundle.putString("iccId",motorInfo.getIccid());
                        bundle.putString("typeName", motorInfo.getTypeName());
                        bundle.putString("circumference", motorInfo.getCircumference() + "");
                        bundle.putString("statusCode",statusCode);
                        App.getInstance().setMotor(motorInfo);
                        Intent intent = new Intent(IotBluetoothListActivity.this,IotParamSetActivity.class);
                        intent.putExtra("bundle",bundle);
                        startActivity(intent);
                        finish();
                    } else {
                        showToastMsg(getString(R.string.toast_iotIndex_bleNoMotor));
                        BluetoothLEService.disConnect();
                    }
                } else {
                    showToastMsg(IotHttpHelp.source2Message(IotBluetoothListActivity.this, source));
                    BluetoothLEService.disConnect();
                }
            }
        });
    }
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void scanLeDevice(final boolean enable) {
        if (enable) {   //启动扫描
            mScanning = true;
            mImgRefresh.startAnimation(mOperatingAnim);
            mTvScan.setText(getString(R.string.bluetoothList_stop));
            mBluetoothAdapter.startLeScan(mLeScanCallback);
            mHandler.postDelayed(new Runnable() {
                @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
                @Override
                public void run() {
                    mScanning = false;
                    mImgRefresh.clearAnimation();
                    mTvScan.setText(getString(R.string.bluetoothList_scan));
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                    invalidateOptionsMenu();
                }
            }, SCAN_PERIOD);    //25秒后停止扫描
        } else {    //停止扫描
            mScanning = false;
            mImgRefresh.clearAnimation();
            mTvScan.setText(getString(R.string.bluetoothList_scan));
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
        invalidateOptionsMenu();
    }
    /**
     * 注册广播接收器
     */
    private void registerBroadcast(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConstantsValue.ACTION_BLUETOOTH_CONNECT_STATE_CHANGED);
        registerReceiver(broadcastReceiver, filter);
    }
    @Override
    protected void onResume() {
        super.onResume();
        // 为了确保设备上蓝牙能使用, 如果当前蓝牙设备没启用,弹出对话框向用户要求授予权限来启用
        if (!mBluetoothAdapter.isEnabled()) {
            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        }
        mLeDeviceListAdapter = new BluetoothListAdapter(this, mBluetoothInfoBeanList);
        mLstBluetooth.setAdapter(mLeDeviceListAdapter);
        scanLeDevice(true);
    }
    @Override
    protected void onPause() {
        super.onPause();
        mLstScanedAddress.clear();
        mBluetoothInfoBeanList.clear();
        scanLeDevice(false);
        mIsOnShow = false;
    }
    @Override
    public void finish() {
        super.finish();
        BluetoothLEService.disConnect();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
        BluetoothLEService.disConnect();
    }
}
